package com.shanjupay.merchant.servicve.impl;

import com.alibaba.fastjson.JSON;
import com.shanjupay.merchant.servicve.SmsCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@org.springframework.stereotype.Service
@Slf4j
public class SmsCodeServiceImpl implements SmsCodeService {
    @Autowired
    RestTemplate restTemplate;

    @Value("${sms.url}")
    private String uri;

    @Value("${sms.effectiveTime}")
    private Integer effectiveTime;

    /**
     * 获取验证码
     *
     * @param phone 手机号
     * @return
     */
    @Override
    public String getSmsCode(String phone) {

        //设置基础请求
        String url = uri + "/generate?name=sms&effectiveTime=" + effectiveTime;
        //设置手机号
        HashMap<String, Object> body = new HashMap<>();
        body.put("mobile", phone);

        //设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        //封装请求参数
        HttpEntity httpEntity = new HttpEntity(body, httpHeaders);

        //发送请求 （POST）
        ResponseEntity<Map> exchange = null;
        try {
            exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            throw new RuntimeException("验证码发送失败");
        }
        //健壮性判断
        if (exchange == null || exchange.getBody() == null || exchange.getBody().get("result") == null) {
            throw new RuntimeException("验证码发送失败");
        }

        //解析请求
        Map bodyMap = exchange.getBody();
        Map result = (Map) bodyMap.get("result");

        //获取 key
        String key = (String) result.get("key");
        return key;
    }


    /**
     * 校验验证码
     *
     * @param verifiyKey
     * @param verifiyCode
     */
    @Override
    public void checkVerifiyCode(String verifiyKey, String verifiyCode) {
        //路径
        String url = uri + "/verify?name=sms&verificationCode="+verifiyCode+"&verificationKey="+verifiyKey;

        Map responseMap = null;
        try {
            //请求校验验证码
            ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST,
                    HttpEntity.EMPTY, Map.class);
            responseMap = exchange.getBody();
            log.info("校验验证码，响应内容：{}", JSON.toJSONString(responseMap));
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage(), e);
            throw new RuntimeException("验证码错误");
        }
        if (responseMap == null || responseMap.get("result") == null || !(Boolean)
                responseMap.get("result")) {
            throw new RuntimeException("验证码错误");
        }

    }
}
